package com.example.allshengmedical.experimentrun.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.text.Selection;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.allsheng.widget.AllShengDialog;
import com.allsheng.widget.AllShengDialog.ClickListenerInterface;
import com.example.allshengmedical.R;
import com.example.allshengmedical.base.BaseActivity;
import com.example.allshengmedical.base.BaseApplication;
import com.example.allshengmedical.experimentanalyze.activity.AnalyzeAmplificationplotActivity;
import com.example.allshengmedical.experimentanalyze.activity.AnalyzeBrowseActivity;
import com.example.allshengmedical.experimentnew.activity.EditMethodsActivity.RecyclerViewAdapter;
import com.example.allshengmedical.experimentnew.bean.LayoutTableBean;
import com.example.allshengmedical.experimentnew.bean.MethodBean;
import com.example.allshengmedical.experimentrun.presenter.RunMethodPresenter;
import com.example.allshengmedical.experimentrun.view.IRunMethodView;
import com.example.allshengmedical.mainmenu.activity.MainMenuActivity;
import com.example.allshengmedical.util.ByAlert;
import com.example.allshengmedical.util.FileManagerUtil;
import com.example.allshengmedical.util.LogUtil;
import com.example.allshengmedical.util.MyHorizontalScrollView;
import com.example.allshengmedical.util.ScrollViewListener;
import com.example.allshengmedical.util.SharedPreferencesUtils;
import com.example.allshengmedical.util.SimpleLineChart;
import com.itboye.allshengmedical.sci.DefaultSerialControl;
import com.itboye.allshengmedical.sci.ISerialControl;
import com.itboye.allshengmedical.sci.cmd.req.CmdType;
import com.itboye.allshengmedical.sci.packet.resp.BaseRespPacket;
import com.itboye.allshengmedical.sci.packet.resp.DetectLightIntensitTempRespPacket;
import com.itboye.allshengmedical.sci.packet.resp.GetTempRespPacket;

//运行的方法界面
public class RunMethodActivity extends BaseActivity implements IRunMethodView, ScrollViewListener {
	public final int TASK_LOOP_COMPLETE = 0;
	ProgressDialog pd;
	private RunMethodPresenter runMethodPresenter;

	private ProgressBar progressBar;

	private boolean menuboo;
	private PopupWindow menuPopupWindow;
	PopupWindow upDatePopupWindow;
	// 数据
	String folderName;
	String fileName;
	private String appFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical";
	StringBuffer contextString = new StringBuffer();

	// 曲线图
	// 上半部
	private RecyclerView steptRv;
	private RecyclerViewAdapter recyclerViewAdapter;
	private ArrayList<MethodBean> activityMethodBeans;

	// 下半部分
	private SimpleLineChart mSimpleLineChart;
	private String editTextString;

	// 下面的图表
	HashMap<Integer, Integer> pointMap = new HashMap();
	List<HashMap<String, Object>> pointMaps = new ArrayList<HashMap<String, Object>>();

	private String[] xItem, yItem = { "", "", "", "", "", "", "", "", "", "", "" };

	// 下面的横划
	MyHorizontalScrollView downScrollView, upScrollView;

	TextView start_time, end_time, nowTempMod1, nowTempMod2, nowTempMod3, time_count, phototime_count;
	String hotLidTemperature, sampleVolumeString, readDataString;
	List<LayoutTableBean> activityLayoutTableBeans = new ArrayList<LayoutTableBean>();
	// 基因盘数据
	public List<HashMap<String, Object>> dataSourceListBlock1 = new ArrayList<HashMap<String, Object>>();
	public List<HashMap<String, Object>> dataSourceListBlock2 = new ArrayList<HashMap<String, Object>>();
	ArrayList<String> channelList = new ArrayList<String>();
	HashMap<Integer, ArrayList<ArrayList<Float>>> arrayList = new HashMap<Integer, ArrayList<ArrayList<Float>>>();
	// private boolean isExperimentFinish = false;
	private RunMethodService myservice = null;
	String tempMode1, tempMode2, tempMode3;
	Button leftfirstBtn;
	String stepWhere;
	Button leftsecondBtn, leftThird_btn, leftForth_btn, leftFifth_btn, leftSixth_btn, leftSevenTh_btn, leftEighth_btn,
			leftNineth_btn, rightfirst_btn, leftTenth_btn;
	LinearLayout rightline;
	SQLiteDatabase db;
	TempDBHelper dbHelper;
	TextView showTv;
	int photoBackCount;
	LinearLayout max_lin;
	boolean isStopService = false;
	boolean isFirstFinish = true;

	// PopupWindow popWindow;

	// TempDBManager dbManager;

	@Override
	protected int setcontent() {
		return R.layout.activity_run_method;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void initView() {
		// dbManager = new TempDBManager(this);
		dbHelper = new TempDBHelper(RunMethodActivity.this);
		Intent intent = getIntent();
		dataSourceListBlock1 = (List<HashMap<String, Object>>) intent.getSerializableExtra("dataSourceListBlock1");
		dataSourceListBlock2 = (List<HashMap<String, Object>>) intent.getSerializableExtra("dataSourceListBlock2");
		activityLayoutTableBeans = (ArrayList<LayoutTableBean>) intent.getSerializableExtra("activityLayoutTableBeans");
		IntentFilter filter = new IntentFilter("ProgressSpeed");
		registerReceiver(progressReceiver, filter);
		IntentFilter tempFilter = new IntentFilter("TempDate");
		registerReceiver(tempReceiver, tempFilter);
		IntentFilter photoBackCount = new IntentFilter("photoBackCount");
		registerReceiver(photoBackCountReceiver, tempFilter);
		IntentFilter finishIntentFilter = new IntentFilter("ExperimentFinish");
		registerReceiver(finisBroadcastReceiver, finishIntentFilter);
		startTime();
		downScrollView = BindView(R.id.downScrollView);
		downScrollView.setScrollViewListener(this);
		upScrollView = BindView(R.id.upScrollView);
		upScrollView.setScrollViewListener(this);

		runMethodPresenter = new RunMethodPresenter(this);
		runMethodPresenter.initAppHead();
		// runMethodPresenter.initBottomView();
		runMethodPresenter.getInfo();
		runMethodPresenter.initSimpleLineChart();

		SharedPreferences preferences = getSharedPreferences("ExperimentFinish", Context.MODE_PRIVATE);
		if (preferences.getBoolean("isFinish", false)) {
			leftfirstBtn.setEnabled(true);
			rightfirst_btn.setEnabled(false);
			time_count.setText("00:00:00");
		}
		IntentFilter isPopFinishFilter = new IntentFilter("isPopFinish");
		registerReceiver(isPopFinishReceiver, isPopFinishFilter);
	}

	BroadcastReceiver isPopFinishReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			// if (popWindow.isShowing()) {
			// backgroundAlpaha(RunMethodActivity.this, 1f);
			// popWindow.dismiss();
			// popWindow = null;
			// }
		}

	};
	BroadcastReceiver photoBackCountReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			SharedPreferences preferences = getSharedPreferences("photoBackCount", Context.MODE_PRIVATE);
			phototime_count.setText(preferences.getString("phototime_count", "0"));
			photoBackCount = Integer.parseInt(preferences.getString("phototime_count", "0"));
		}

	};
	BroadcastReceiver finisBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			try {
				closeProgressDialog();
				for (MethodBean bean : activityMethodBeans) {
					bean.setSelected(false);
				}
				recyclerViewAdapter.notifyDataSetChanged();
			} catch (Exception e) {
				// TODO: handle exception
			}
			leftfirstBtn.setEnabled(true);
			rightfirst_btn.setEnabled(false);
			time_count.setText("00:00:00");
			progressBar.setProgress(100);
			// if (isFirstFinish) {
			// if (null == popWindow || !popWindow.isShowing()) {
			// showReturnPop();
			// isFirstFinish = false;
			// }
			// }

		}

	};
	BroadcastReceiver tempReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			startTime();
			tempMode1 = intent.getStringExtra("tempMod1");
			tempMode2 = intent.getStringExtra("tempMod2");
			tempMode3 = intent.getStringExtra("tempMod3");
			stepWhere = intent.getStringExtra("step");
			for (MethodBean bean : activityMethodBeans) {
				bean.setSelected(false);
			}

			if (intent.getStringExtra("tempMod1") != null && !"".equals(intent.getStringExtra("tempMod1"))) {
				nowTempMod1.setText(intent.getStringExtra("tempMod1"));
				nowTempMod2.setText(intent.getStringExtra("tempMod2"));
				nowTempMod3.setText(intent.getStringExtra("tempMod3"));
				if (Integer.parseInt(stepWhere) < activityMethodBeans.size()) {
					activityMethodBeans.get(Integer.parseInt(stepWhere)).setSelected(true);
					recyclerViewAdapter.notifyDataSetChanged();
				}

			} else {
				SharedPreferences preferences = getSharedPreferences("Temp", Context.MODE_PRIVATE);
				nowTempMod1.setText(preferences.getString("tempMod1", ""));
				nowTempMod2.setText(preferences.getString("tempMod2", ""));
				nowTempMod3.setText(preferences.getString("tempMod3", ""));
				if (Integer.parseInt(preferences.getString("step", "0")) < activityMethodBeans.size()) {
					activityMethodBeans.get(Integer.parseInt(preferences.getString("step", "0"))).setSelected(true);
					recyclerViewAdapter.notifyDataSetChanged();
				}
			}

		}

	};

	public void backgroundAlpaha(Activity context, float bgAlpha) {
		WindowManager.LayoutParams lp = context.getWindow().getAttributes();
		lp.alpha = bgAlpha;
		context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		context.getWindow().setAttributes(lp);
	}

	private void isDismiss() {
		Intent intent = new Intent("isPopFinish");
		intent.putExtra("isPopFinish", true);
		sendBroadcast(intent);
	}

	// private void showReturnPop() {
	// LayoutInflater inflater = (LayoutInflater) (RunMethodActivity.this)
	// .getSystemService(LAYOUT_INFLATER_SERVICE);
	// View popview = inflater.inflate(R.layout.pop_return_pop, null);
	// popWindow = new PopupWindow(popview, LayoutParams.WRAP_CONTENT,
	// LayoutParams.WRAP_CONTENT);
	// ImageView closeimg = (ImageView) popview.findViewById(R.id.img_closed);
	// TextView txt_returnmain = (TextView) popview
	// .findViewById(R.id.txt_returnmain);
	// popWindow.setTouchable(true);
	// popWindow.setOutsideTouchable(true);
	// TextView txt_returnanylse = (TextView) popview
	// .findViewById(R.id.txt_returnanylse);
	// ColorDrawable dw = new ColorDrawable(0xb0000000);
	// popWindow.setBackgroundDrawable(dw);
	// popWindow.setOnDismissListener(new poponDismissListener());
	// // popWindow.setBackgroundDrawable(new ColorDrawable());
	// backgroundAlpaha(RunMethodActivity.this, 0.5f);
	// if (popWindow == null || !popWindow.isShowing()) {
	// popWindow.showAtLocation(max_lin, Gravity.CENTER, 0, 0);
	// }
	// if (isStopService) {
	// txt_returnanylse.setVisibility(View.GONE);
	// }
	// closeimg.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View arg0) {
	// // TODO Auto-generated method stub
	// popWindow.dismiss();
	// isDismiss();
	// }
	// });
	// txt_returnmain.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View arg0) {
	// // TODO Auto-generated method stub
	// BaseApplication.getInstance().finishAll();
	// Intent intent = new Intent(RunMethodActivity.this,
	// MainMenuActivity.class);
	// startActivity(intent);
	// overridePendingTransition(0, 0);
	// popWindow.dismiss();
	// }
	// });
	// txt_returnanylse.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View arg0) {
	// // TODO Auto-generated method stub
	// BaseApplication.getInstance().finishAll();
	// Intent intent = new Intent(RunMethodActivity.this,
	// AnalyzeAmplificationplotActivity.class);
	// startActivity(intent);
	// overridePendingTransition(0, 0);
	// popWindow.dismiss();
	// }
	// });
	// }

	// public ServiceConnection conn = new ServiceConnection() {
	//
	// @Override
	// public void onServiceConnected(ComponentName arg0, IBinder arg1) {
	// // TODO Auto-generated method stub
	// myservice = ((RunMethodService.MyBinder) arg1).getService();
	// }
	//
	// @Override
	// public void onServiceDisconnected(ComponentName arg0) {
	// // TODO Auto-generated method stub
	// myservice = null;
	// }
	// };

	private void startTime() {
		SharedPreferences preferences = getSharedPreferences("Time", Context.MODE_PRIVATE);

		start_time.setText(preferences.getString("startTime", null));
		end_time.setText(preferences.getString("endTime", null));
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	public void initAppHead() {
		setActionBar();
		setSystemTime();

	}

	@Override
	public void initBottomView() {
		// setBottomView();

	}

	BroadcastReceiver progressReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String progressString = intent.getStringExtra("Progress");
			String nowString = intent.getStringExtra("NowTime");
			time_count.setText(nowString);
			progressBar.setProgress(Integer.parseInt(progressString));
			// if (Integer.parseInt(progressString)>=100) {
			// progressBar.setVisibility(View.INVISIBLE);
			//
			// }
		}

	};
	BroadcastReceiver timeReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			Log.e("hu.reg.star", intent.getStringExtra("startTime"));
			start_time.setText(intent.getStringExtra("startTime"));
			end_time.setText(intent.getStringExtra("endTime"));
		}

	};

	@Override
	public void getInfo() {
		folderName = SharedPreferencesUtils.get(RunMethodActivity.this, BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
				"") + "";
		fileName = SharedPreferencesUtils.get(RunMethodActivity.this, BaseApplication.FILEMANGER_PREPAREFILENAME, "")
				+ "";

		String path = appFilePath + "/" + folderName;

		File file = new File(path + "/" + fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行:");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				// System.out.println("line " + line + ": " + tempString);
				// Log.e("--", tempString);
				contextString.append(tempString);
				contextString.append(",");
				line++;
				SystemClock.sleep(1);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
					// LogUtil.e("!!", contextString + "");

				} catch (IOException e1) {
				}
			}
		}
	}

	@Override
	public void initSimpleLineChart() {
		initSimpleLineChartView();

	}

	@Override
	public void initListView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMessage() {
		// TODO Auto-generated method stub

	}

	// 设置actionBar
	public void setActionBar() {

		// TextView title;
		leftfirstBtn = BindView(R.id.leftfirst_btn);
		leftsecondBtn = BindView(R.id.leftsecond_btn);
		leftThird_btn = BindView(R.id.leftThird_btn);
		leftForth_btn = BindView(R.id.leftForth_btn);

		leftFifth_btn = BindView(R.id.leftFifth_btn);
		leftSixth_btn = BindView(R.id.leftSixth_btn);
		leftSevenTh_btn = BindView(R.id.leftSevenTh_btn);
		leftEighth_btn = BindView(R.id.leftEighth_btn);
		leftNineth_btn = BindView(R.id.leftNineth_btn);
		leftTenth_btn = BindView(R.id.leftTenth_btn);

		rightfirst_btn = BindView(R.id.rightfirst_btn);
		rightline = BindView(R.id.rightline);
		// title = BindView(R.id.title);

		leftSixth_btn.setVisibility(View.GONE);
		leftSevenTh_btn.setVisibility(View.GONE);
		leftEighth_btn.setVisibility(View.GONE);
		leftNineth_btn.setVisibility(View.GONE);
		leftTenth_btn.setVisibility(View.GONE);
		leftfirstBtn.setVisibility(View.VISIBLE);
		leftfirstBtn.setText(R.string.item_actionbar_home);
		leftsecondBtn.setVisibility(View.VISIBLE);
		leftsecondBtn.setText(getString(R.string.Run_Amplification));
		leftForth_btn.setSelected(true);
		leftThird_btn.setVisibility(View.VISIBLE);
		leftThird_btn.setText(getString(R.string.Run_Teperature1));
		leftForth_btn.setVisibility(View.VISIBLE);
		leftForth_btn.setText(getString(R.string.Run_Method));
		SharedPreferences preferences = getSharedPreferences("Delet", Context.MODE_PRIVATE);
		if (preferences.getBoolean("Delet", false)) {
			leftFifth_btn.setVisibility(View.VISIBLE);
			leftFifth_btn.setText(getString(R.string.Run_MeltCurve));
		} else {
			leftFifth_btn.setVisibility(View.GONE);

		}
		rightfirst_btn.setVisibility(View.VISIBLE);
		rightfirst_btn.setText(getString(R.string.Run_Stop));
		rightline.setVisibility(View.VISIBLE);
		// title.setText("Amplifucation Plot");
		leftfirstBtn.setEnabled(false);

		leftfirstBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				BaseApplication.getInstance().finishAll();
				Intent intent = new Intent(RunMethodActivity.this, MainMenuActivity.class);
				startActivity(intent);
				overridePendingTransition(0, 0);
				stopService(new Intent(RunMethodActivity.this, RunMethodService.class));
			}

		});

		leftsecondBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
//				pd = ProgressDialog.show(RunMethodActivity.this, "",
//						"loading...", true, true);
//
//				new Thread() {
//					public void run() {
//						try {
							Intent intent = new Intent(RunMethodActivity.this, AmplifucationActivity.class);
							intent.putExtra("dataSourceListBlock1", (Serializable) dataSourceListBlock1);
							intent.putExtra("dataSourceListBlock2", (Serializable) dataSourceListBlock2);
							intent.putExtra("activityLayoutTableBeans", (Serializable) activityLayoutTableBeans);
							startActivity(intent);
							overridePendingTransition(0, 0);
//						} finally {
//							messageListener
//									.sendEmptyMessage(TASK_LOOP_COMPLETE);
//						}
//					}
//				}.start();

			
			}
		});
		leftThird_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				pd = ProgressDialog.show(RunMethodActivity.this, "",
//						"loading...", true, true);
//
//				new Thread() {
//					public void run() {
//						try {
							Intent intent = new Intent(RunMethodActivity.this, TemparetureActivity.class);
							intent.putExtra("dataSourceListBlock1", (Serializable) dataSourceListBlock1);
							intent.putExtra("dataSourceListBlock2", (Serializable) dataSourceListBlock2);
							intent.putExtra("activityLayoutTableBeans", (Serializable) activityLayoutTableBeans);
							startActivity(intent);
							overridePendingTransition(0, 0);
//						} finally {
//							messageListener
//									.sendEmptyMessage(TASK_LOOP_COMPLETE);
//						}
//					}
//				}.start();
				
			}
		});
		leftForth_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				pd = ProgressDialog.show(RunMethodActivity.this, "",
//						"loading...", true, true);
//
//				new Thread() {
//					public void run() {
//						try {
//							Intent intent = new Intent(RunMethodActivity.this, RunMethodActivity.class);
//							intent.putExtra("dataSourceListBlock1", (Serializable) dataSourceListBlock1);
//							intent.putExtra("dataSourceListBlock2", (Serializable) dataSourceListBlock2);
//							intent.putExtra("activityLayoutTableBeans", (Serializable) activityLayoutTableBeans);
//							startActivity(intent);
//							overridePendingTransition(0, 0);
//						} finally {
//							messageListener
//									.sendEmptyMessage(TASK_LOOP_COMPLETE);
//						}
//					}
//				}.start();
			
			}
		});
		leftFifth_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				pd = ProgressDialog.show(RunMethodActivity.this, "",
//						"loading...", true, true);
//
//				new Thread() {
//					public void run() {
//						try {
							Intent intent = new Intent(RunMethodActivity.this, AmplifucationTwoActivity.class);
							intent.putExtra("dataSourceListBlock1", (Serializable) dataSourceListBlock1);
							intent.putExtra("dataSourceListBlock2", (Serializable) dataSourceListBlock2);
							intent.putExtra("activityLayoutTableBeans", (Serializable) activityLayoutTableBeans);
							startActivity(intent);
							overridePendingTransition(0, 0);
//						} finally {
//							messageListener
//									.sendEmptyMessage(TASK_LOOP_COMPLETE);
//						}
//					}
//				}.start();
				
			}
		});
		rightfirst_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final AllShengDialog allShengDialog = new AllShengDialog(RunMethodActivity.this, "", "确定要停止实验吗", "OK",
						"NO");
				allShengDialog.show();
				allShengDialog.setClicklistener(new ClickListenerInterface() {

					@Override
					public void OK() {
						// TODO Auto-generated method stub
						isStopService = true;
						Intent intent = new Intent("StopService");
						sendBroadcast(intent);
						showProgressDialog("正在降温....", true);
						allShengDialog.dismiss();

					}

					@Override
					public void Cancle() {
						// TODO Auto-generated method stub
						allShengDialog.dismiss();

					}
				});
			}
		});

	}
	private Handler messageListener = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.arg1) {
			case TASK_LOOP_COMPLETE:
				pd.dismiss();
				break;

			}
		}
	};

	// 获取当前时间的方法
	public void setSystemTime() {

		TextView date, fileName;
		date = BindView(R.id.date);
		fileName = BindView(R.id.file_name);

		// 获取系统时间
		SimpleDateFormat sdfDate = new SimpleDateFormat("MM dd,yyyy");
		date.setText(sdfDate.format(new Date()));

		// 文件路径置空
		fileName.setText(SharedPreferencesUtils.get(this, BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "") + "/"
				+ SharedPreferencesUtils.get(this, BaseApplication.FILEMANGER_PREPAREFILENAME, ""));

	}

	private void setBottomView() {
		Button bottomLeftFistBtn, bottomCenterBtn, bottomRightBtn;

		bottomLeftFistBtn = BindView(R.id.bottomLeftFistBtn);
		bottomCenterBtn = BindView(R.id.bottomCenterBtn);
		bottomRightBtn = BindView(R.id.bottomRightBtn);

		bottomLeftFistBtn.setVisibility(View.VISIBLE);
		bottomCenterBtn.setVisibility(View.VISIBLE);
		bottomRightBtn.setVisibility(View.VISIBLE);

		bottomLeftFistBtn.setText(R.string.bottomView_back);
		// TODO 这个button的文字不确定暂时用A代替
		bottomCenterBtn.setText("A"); // 不确定！！！！！！！
		bottomRightBtn.setText(R.string.bottomView_next);

		bottomLeftFistBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// ByAlert.alert("back");
				finish();

			}
		});

		bottomCenterBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ByAlert.alert("A");

			}
		});
		bottomRightBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(RunMethodActivity.this,
				// AmplifucationActivity.class);
				//
				// startActivity(intent);
			}
		});

	}

	private void initSimpleLineChartView() {
		editTextString = contextString.substring(contextString.indexOf(",,Methods,,"), contextString.length());

		mSimpleLineChart = (SimpleLineChart) findViewById(R.id.simpleLineChart);
		activityMethodBeans = new ArrayList<MethodBean>();

		int index = editTextString.indexOf("Methods");
		// 上面解析
		while (!(editTextString.indexOf("steptType:", index) <= 0)) {

			// steptType:
			String steptType;
			steptType = editTextString.substring(editTextString.indexOf("steptType:", index) + 10,

					editTextString.indexOf(",temperature:", index));

			// LogUtil.e(steptType);

			// temperature
			String temperature;
			temperature = editTextString.substring(editTextString.indexOf(",temperature:", index) + 13,

					editTextString.indexOf(",time:", index));

			// LogUtil.e(temperature);
			// time
			String time;
			time = editTextString.substring(editTextString.indexOf(",time:", index) + 6,

					editTextString.indexOf(",goTo:", index));
					// LogUtil.e(time);

			// goTo
			String goTo;
			goTo = editTextString.substring(editTextString.indexOf(",goTo:", index) + 6,

					editTextString.indexOf(",Repititions:", index));
			// LogUtil.e(goTo);
			// Repititions
			String repititions;
			repititions = editTextString.substring(editTextString.indexOf(",Repititions:", index) + 13,

					editTextString.indexOf(",deltaT:", index));
			// LogUtil.e(repititions);
			// deltaT
			String deltaT;
			deltaT = editTextString.substring(editTextString.indexOf(",deltaT:", index) + 8,

					editTextString.indexOf(",rightSelect:", index));
			// LogUtil.e(deltaT);

			int nextIndex = editTextString.indexOf("steptType:", index) + 10;

			// rightSelect
			Boolean rightSelect;

			if (editTextString.indexOf(",steptType:", nextIndex) < 0) {
				rightSelect = Boolean
						.parseBoolean(editTextString.substring(editTextString.indexOf(",rightSelect:", index) + 13,
								editTextString.indexOf(",,pointMap", index)).trim());
				if ("null".equals(rightSelect)) {
					rightSelect = false;
				}

			} else {
				rightSelect = Boolean
						.parseBoolean(editTextString.substring(editTextString.indexOf(",rightSelect:", index) + 13,

								editTextString.indexOf(",steptType:", nextIndex)).trim());
				if ("null".equals(rightSelect)) {
					rightSelect = false;
				}
			}
			// LogUtil.e(rightSelect);
			index = editTextString.indexOf(",rightSelect:", index) + 13;
			hotLidTemperature = contextString.substring(contextString.indexOf("hotLidTemperature:") + 18,
					contextString.indexOf(",sampleVolumeString:"));
			sampleVolumeString = contextString.substring(contextString.indexOf("sampleVolumeString:") + 19,
					contextString.indexOf(",readDataString:"));
			readDataString = contextString.substring(contextString.indexOf("readDataString:") + 15,
					contextString.indexOf(",,", contextString.indexOf("readDataString:")));

			activityMethodBeans.add(new MethodBean(steptType.trim(), temperature.trim(), time.trim(), goTo.trim(),
					repititions.trim(), deltaT.trim(), rightSelect));

		}
		// 上面配置完成
		steptRv = BindView(R.id.steptRv);
		LayoutManager layoutManager = new GridLayoutManager(this, 1);
		((GridLayoutManager) layoutManager).setOrientation(OrientationHelper.HORIZONTAL);
		steptRv.setLayoutManager(layoutManager);
		recyclerViewAdapter = new RecyclerViewAdapter(activityMethodBeans);
		steptRv.setAdapter(recyclerViewAdapter);

		// 下面解析
		int num = 1;
		pointMap = new HashMap<Integer, Integer>();
		if (editTextString.indexOf(",,Channel1") > 0) {
			// 已经有实验数据的实验
			while (!(editTextString.indexOf("pointMap", index) <= 0)) {

				int pointMapValue = 0;
				// int nextIndex = contextString.indexOf("pointMap", index);

				if (editTextString.indexOf("pointMap" + num) < 0) {
					// pointMap = Integer
					// .parseInt(contextString.substring(contextString
					// .indexOf("pointMap"+num, index) + 10));

				} else {
					if (editTextString.indexOf("pointMap" + (num + 1)) < 0) {
						// pointMap = Integer.parseInt(contextString
						// .substring(
						// contextString.indexOf("pointMap:" + num,
						// index) + 9).trim());
						if (num < 10) {

							pointMapValue = 10 - Integer
									.parseInt(editTextString.substring(editTextString.indexOf("pointMap" + num) + 11,
											editTextString.indexOf(",,Raw Data")).trim());
						} else {
							pointMapValue = 10 - Integer
									.parseInt(editTextString.substring(editTextString.indexOf("pointMap" + num) + 11,
											editTextString.indexOf(",,Raw Data")).trim());
						}

						// LogUtil.e(pointMapValue);
						pointMap.put(num - 1, pointMapValue);
						break;

					} else {

						if (num < 10) {
							pointMapValue = 10
									- Integer
											.parseInt(
													editTextString
															.substring(editTextString.indexOf("pointMap" + num) + 10,
																	editTextString.indexOf(",pointMap" + (num + 1)))
															.trim());
						} else {
							pointMapValue = 10
									- Integer
											.parseInt(
													editTextString
															.substring(editTextString.indexOf("pointMap" + num) + 11,
																	editTextString.indexOf(",pointMap" + (num + 1)))
															.trim());
						}

					}

				}
				pointMap.put(num - 1, pointMapValue);
				num++;
				index = editTextString.indexOf("pointMap", index);
				// LogUtil.e(pointMapValue);

			}
		} else {
			while (!(editTextString.indexOf("pointMap", index) <= 0)) {

				int pointMapValue = 0;
				// int nextIndex = contextString.indexOf("pointMap", index);

				if (editTextString.indexOf("pointMap" + num) < 0) {
					// pointMap = Integer
					// .parseInt(contextString.substring(contextString
					// .indexOf("pointMap"+num, index) + 10));

				} else {
					if (editTextString.indexOf("pointMap" + (num + 1)) < 0) {
						// pointMap = Integer.parseInt(contextString
						// .substring(
						// contextString.indexOf("pointMap:" + num,
						// index) + 9).trim());
						if (num < 10) {
							// pointMapValue = Integer.parseInt(contextString
							// .substring(
							// contextString.indexOf("pointMap"
							// + num) + 10).trim());

							String xString = editTextString.substring(editTextString.indexOf("pointMap" + num) + 10);
							if (xString.indexOf("Temp Data") > 0) {
								xString = xString.substring(0, xString.indexOf(",Temp Data"));
							}
							if (!(",,".equals(xString))) {
								pointMapValue = 10
										- Integer.parseInt(xString.substring(0, xString.length() - 1).trim());
							}

							// (contextString.substring(contextString
							// .indexOf("pointMap" + num) + 10))
							// .substring((contextString.substring(
							// contextString.indexOf("pointMap"
							// + num) + 10).length() - 1));

						} else {
							String xString = editTextString.substring(editTextString.indexOf("pointMap" + num) + 11)
									.trim().substring(0,
											editTextString.substring(editTextString.indexOf("pointMap" + num) + 11)
													.trim().length() - 1);
							if (xString.indexOf("Temp Data") > 0) {
								xString = xString.substring(0, xString.indexOf(",,Temp Data"));
							}
							pointMapValue = 10 - Integer.parseInt(xString);
						}

						// LogUtil.e(pointMapValue);
						pointMap.put(num - 1, pointMapValue);
						break;

					} else {

						if (num < 10) {
							pointMapValue = 10
									- Integer
											.parseInt(
													editTextString
															.substring(editTextString.indexOf("pointMap" + num) + 10,
																	editTextString.indexOf(",pointMap" + (num + 1)))
															.trim());
						} else {
							pointMapValue = 10
									- Integer
											.parseInt(
													editTextString
															.substring(editTextString.indexOf("pointMap" + num) + 11,
																	editTextString.indexOf(",pointMap" + (num + 1)))
															.trim());
						}

					}

				}
				pointMap.put(num - 1, pointMapValue);
				num++;
				index = editTextString.indexOf("pointMap", index);
				// LogUtil.e(pointMapValue);

			}
		}

		// LogUtil.e(pointMap);

		// pointmaps
		pointMaps = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < 40; i++) {
			HashMap<String, Object> itemHashMap = new HashMap<String, Object>();
			// x
			itemHashMap.put("x", i);
			// y
			itemHashMap.put("y", "");
			// 温度
			itemHashMap.put("temperature", "");
			// 时间
			itemHashMap.put("time", "");
			// DeltaT
			itemHashMap.put("deltaT", "");
			// gotTo
			itemHashMap.put("goTo", "");
			// Repititions
			itemHashMap.put("repititions", "");
			pointMaps.add(itemHashMap);

		}
		// 初始化
		mSimpleLineChart = BindView(R.id.simpleLineChart);
		mSimpleLineChart.setData(pointMap);
		mSimpleLineChart.setData2(pointMaps);
		String[] yItem = { "", "", "", "", "", "", "", "", "", "", "" };
		mSimpleLineChart.setYItem(yItem);
		// controlInstance = DefaultSerialControl.getInstance();
		// controlInstance.init();
		// controlInstance.start();
		// controlInstance.setHandler(mHandler);

		UpdateView();

	}

	private void UpdateView() {

		switch (pointMap.size()) {
		case 0:
			xItem = new String[] { "" };
			break;
		case 1:
			xItem = new String[] { "Step1" };
			break;
		case 2:
			xItem = new String[] { "Step1", "", };
			break;
		case 3:
			xItem = new String[] { "Step1", "", "Step2" };
			break;
		case 4:
			xItem = new String[] { "Step1", "", "Step2", "" };
			break;
		case 5:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3" };
			break;
		case 6:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "" };
			break;

		case 7:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4" };
			break;
		case 8:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "" };
			break;
		case 9:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5" };
			break;
		case 10:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "" };
			break;
		case 11:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6" };
			break;
		case 12:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "" };
			break;
		case 13:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7" };
			break;
		case 14:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "" };
			break;
		case 15:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8" };
			break;
		case 16:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "" };
			break;
		case 17:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9" };
			break;
		case 18:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "" };
			break;
		case 19:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10" };
			break;
		case 20:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "" };
			break;
		case 21:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11" };
			break;
		case 22:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "" };
			break;
		case 23:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12" };
			break;
		case 24:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "" };
			break;
		case 25:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13" };
			break;
		case 26:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "" };
			break;
		case 27:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14" };
			break;
		case 28:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "" };
			break;
		case 29:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15" };
			break;
		case 30:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "" };
			break;
		case 31:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16" };
			break;
		case 32:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "" };
			break;
		case 33:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17" };
			break;
		case 34:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17", "" };
			break;
		case 35:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17", "", "Step18" };
			break;
		case 36:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17", "", "Step18", "" };
			break;
		case 37:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17", "", "Step18", "", "Step19" };
			break;
		case 38:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17", "", "Step18", "", "Step19", "" };
			break;
		case 39:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17", "", "Step18", "", "Step19", "", "Step20" };
			break;
		case 40:
			xItem = new String[] { "Step1", "", "Step2", "", "Step3", "", "Step4", "", "Step5", "", "Step6", "",
					"Step7", "", "Step8", "", "Step9", "", "Step10", "", "Step11", "", "Step12", "", "Step13", "",
					"Step14", "", "Step15", "", "Step16", "", "Step17", "", "Step18", "", "Step19", "", "Step20", "" };

			break;

		default:
			break;
		}
		mSimpleLineChart.setXItem(xItem);
		int timeOne = 0;
		for (int i = 0; i < activityMethodBeans.size(); i++) {
			pointMaps.get(i).put("temperature", activityMethodBeans.get(i).getTemperature());
			pointMaps.get(i).put("time", activityMethodBeans.get(i).getTime());
			pointMaps.get(i).put("deltaT", activityMethodBeans.get(i).getDeltaT());
			pointMaps.get(i).put("gotTo", activityMethodBeans.get(i).getGoTo());
			pointMaps.get(i).put("repititions", activityMethodBeans.get(i).getRepititions());
		}
		// firstTemp = Double.parseDouble(activityMethodBeans.get(0)
		// .getTemperature()) * 10;
		// firstTime = activityMethodBeans.get(0).getTime();
		mSimpleLineChart.setData(pointMap);
		mSimpleLineChart.setData2(pointMaps);
		// Test test = new Test(activityMethodBeans);
		// test.main();
		// Thread Timethread = new Thread(timeRunnable);
		// Timethread.start();
		// SystemClock.sleep(500);

	}

	public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

		ArrayList<MethodBean> methodBeans = new ArrayList<MethodBean>();

		public RecyclerViewAdapter(ArrayList<MethodBean> methodBeans) {
			super();
			this.methodBeans = methodBeans;
		}

		class MyViewHolder extends ViewHolder {

			TextView titleTv;
			LinearLayout orline, line;
			ImageView exitBtn, cameraIv;

			public MyViewHolder(View view) {
				super(view);
				// temperatureTv = (TextView) view
				// .findViewById(R.id.temperatureTv);
				// timeTv = (TextView) view.findViewById(R.id.timeTv);
				// deltaTTv = (TextView) view.findViewById(R.id.deltaTTv);
				line = (LinearLayout) view.findViewById(R.id.line);
				titleTv = (TextView) view.findViewById(R.id.titleTv);
				orline = (LinearLayout) view.findViewById(R.id.orline);
				exitBtn = (ImageView) view.findViewById(R.id.exitBtn);
				cameraIv = (ImageView) view.findViewById(R.id.cameraIv);
			}
		}

		@Override
		public int getItemCount() {
			return methodBeans.size() >= 0 ? methodBeans.size() : 0;
		}

		@Override
		public int getItemViewType(int position) {

			if (position == methodBeans.size()) {
				return 0;
			}

			if ("step".equals(methodBeans.get(position).getSteptType())) {
				return 1;
			} else if ("solubilityCurve".equals(methodBeans.get(position).getSteptType())) {
				return 2;
			}

			return 0;

		}

		@Override
		public void onBindViewHolder(final MyViewHolder holder, final int position) {
			final int index = position + 1;
			if (getItemViewType(position) == 1) {
				// holder.temperatureTv.setText(methodBeans.get(position)
				// .getTemperature());
				// holder.timeTv.setText(methodBeans.get(position).getTime());

				holder.titleTv.setText("Step" + index);
				if (activityMethodBeans.get(position).getRightSelect()) {
					holder.cameraIv.setVisibility(View.VISIBLE);
				} else {
					holder.cameraIv.setVisibility(View.GONE);
				}

				//
				// holder.orline
				// .setOnClickListener(new OnClickListener() {
				//
				// @Override
				// public void onClick(View v) {
				// if (activityMethodBeans.get(position).getRightSelect()) {
				// holder.cameraIv.setVisibility(View.VISIBLE);
				// } else {
				// holder.cameraIv.setVisibility(View.GONE);
				// }
				// if (methodBeans.get(position).getRightSelect()) {
				// for (int i = position; i < methodBeans.size(); i++) {
				// if (!TextUtils.isEmpty(methodBeans.get(position)
				// .getGoTo())) {
				//
				// } else {
				// holder.orline
				// .setBackground(getResources()
				// .getDrawable(
				// R.drawable.step_title_se));
				// holder.titleTv
				// .setTextColor(getResources()
				// .getColor(
				// R.color.white));
				//
				//
				// if (photoBackCount <= (Integer
				// .parseInt(methodBeans.get(
				// position)
				// .getRepititions()) - 4)) {
				// upDatePopupWindow(v, position,
				// holder.titleTv, index);
				// } else {
				// ByAlert.alert("快要循环完了，不建议修改");
				// }
				// }
				// });
				// });
				// }
				// });
				// }
				// if (!TextUtils.isEmpty(methodBeans.get(position).getGoTo()))
				// {
				holder.orline.setTag(position + "");

				holder.orline.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						boolean isshow = true;
						Integer.parseInt(holder.orline.getTag() + "");
						for (int i = Integer.parseInt(holder.orline.getTag() + ""); i < activityMethodBeans
								.size(); i++) {
							if (!TextUtils.isEmpty(activityMethodBeans.get(i).getGoTo())) {
								isshow = false;
							} else {
								isshow = true;
							}
							if (activityMethodBeans.get(position).getRightSelect()) {
								upDatePopupWindow(v, position, holder.titleTv, index);

							}
						}
					}
				});
				// }

			} else if (getItemViewType(position) == 2) {
				// holder.temperatureTv.setText(methodBeans.get(position)
				// .getTemperature());
				// holder.timeTv.setText(methodBeans.get(position).getTime());
				// holder.deltaTTv.setText(methodBeans.get(position).getDeltaT());
				holder.titleTv.setText("Step" + index);

			} else {

			}

			if (methodBeans.get(position).getSelected()) {

				holder.orline.setBackground(getResources().getDrawable(R.drawable.step_title_se));

			} else {
				holder.orline.setBackground(getResources().getDrawable(R.drawable.step_title_un));
			}

		}

		@Override
		public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			if (viewType == 1) {
				MyViewHolder holder = new MyViewHolder(LayoutInflater.from(RunMethodActivity.this)
						.inflate(R.layout.item_methods_step_title, parent, false));
				return holder;
			} else if (viewType == 2) {
				MyViewHolder holder = new MyViewHolder(LayoutInflater.from(RunMethodActivity.this)
						.inflate(R.layout.item_methods_step_title, parent, false));
				return holder;
			} else {
				MyViewHolder holder = new MyViewHolder(LayoutInflater.from(RunMethodActivity.this)
						.inflate(R.layout.item_methods_step_create_new, parent, false));
				return holder;
			}
		}
	}

	@Override
	public void onScrollChanged(MyHorizontalScrollView scrollView, int x, int y, int oldx, int oldy) {
		if (scrollView == downScrollView) {

			upScrollView.smoothScrollTo(x, 0);

		}
		if (scrollView == upScrollView) {
			downScrollView.smoothScrollTo(x, 0);

		}

	}

	private void upDatePopupWindow(final View view, int position, final TextView titleTv, final int index) {
		View convertView = LayoutInflater.from(this).inflate(R.layout.item_run_method_update, null);

		TextView cancelTv, confirmTv, stepNum;
		showTv = (TextView) convertView.findViewById(R.id.showTv);
		cancelTv = (TextView) convertView.findViewById(R.id.cancelTv);
		confirmTv = (TextView) convertView.findViewById(R.id.confirmTv);
		stepNum = (TextView) convertView.findViewById(R.id.stepNum);

		upDatePopupWindow = new PopupWindow(convertView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);

		stepNum.setText("step" + index);

		showTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				numberKeyBoardPopupWindow(view, showTv, true);
			}
		});

		cancelTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				upDatePopupWindow.dismiss();

			}
		});

		confirmTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog(index);
			}
		});

		// upDatePopupWindow.setTouchable(true);
		//
		// upDatePopupWindow.setTouchInterceptor(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// view.setBackground(getResources().getDrawable(
		// R.drawable.step_title_un));
		// titleTv.setTextColor(getResources().getColor(R.color.black));
		// return false;
		// // 这里如果返回true的话，touch事件将被拦截
		// // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
		// }
		//
		// });

		upDatePopupWindow.setBackgroundDrawable(new BitmapDrawable());
		upDatePopupWindow.setOutsideTouchable(true);
		if (!upDatePopupWindow.isShowing()) {
			upDatePopupWindow.showAtLocation(view, Gravity.CENTER, -200, 90);
		}
	}

	// 配置数字键盘的popupwindow
	private void numberKeyBoardPopupWindow(View v, final TextView textv, Boolean type) {
		View conteView = LayoutInflater.from(this).inflate(R.layout.item_numkeyboard, null);

		final EditText showTv;
		TextView num0Tv, num1Tv, num2Tv, num3Tv, num4Tv, num5Tv, num6Tv, num7Tv, num8Tv, num9Tv, num10Tv, cancelTv,
				confirmTv;
		showTv = (EditText) conteView.findViewById(R.id.showTv);
		num0Tv = (TextView) conteView.findViewById(R.id.num0Tv);
		num1Tv = (TextView) conteView.findViewById(R.id.num1Tv);
		num2Tv = (TextView) conteView.findViewById(R.id.num2Tv);
		num3Tv = (TextView) conteView.findViewById(R.id.num3Tv);
		num4Tv = (TextView) conteView.findViewById(R.id.num4Tv);
		num5Tv = (TextView) conteView.findViewById(R.id.num5Tv);
		num6Tv = (TextView) conteView.findViewById(R.id.num6Tv);
		num7Tv = (TextView) conteView.findViewById(R.id.num7Tv);
		num8Tv = (TextView) conteView.findViewById(R.id.num8Tv);
		num9Tv = (TextView) conteView.findViewById(R.id.num9Tv);
		confirmTv = (TextView) conteView.findViewById(R.id.confirmTv);
		cancelTv = (TextView) conteView.findViewById(R.id.cancelTv);

		final PopupWindow numberKeyBoardPopupWindow = new PopupWindow(conteView, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, true);

		confirmTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// if (showTv.getText().length() == 0) {
				// if (R.id.hourTv == textv.getId()) {
				// textv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// minuteTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_darkblueblackframe));
				// } else if (R.id.minuteTv == textv.getId()) {
				//
				// minuteTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// secondTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_darkblueblackframe));
				//
				// } else if (R.id.secondTv == textv.getId()) {
				//
				// secondTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// }
				// numberKeyBoardPopupWindow.dismiss();
				// return;
				// }
				// if (R.id.hourTv == textv.getId()
				// | R.id.minuteTv == textv.getId()
				// | R.id.secondTv == textv.getId()) {
				//
				// if (R.id.hourTv == textv.getId()) {
				// textv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// minuteTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_darkblueblackframe));
				// } else if (R.id.minuteTv == textv.getId()) {
				// int result = Integer.parseInt(showTv.getText()
				// .toString());
				// if (result >= 60) {
				// showTv.setText("");
				// return;
				// }
				// minuteTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// secondTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_darkblueblackframe));
				//
				// showTv.setText(result + "");
				// } else if (R.id.secondTv == textv.getId()) {
				//
				// int result = Integer.parseInt(showTv.getText()
				// .toString());
				// if (result >= 60) {
				// showTv.setText("");
				// return;
				// }
				// secondTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// }
				//
				// DecimalFormat df = new DecimalFormat("00");
				// textv.setText(df.format(Integer.parseInt(showTv.getText()
				// .toString())) + "");
				//
				// numberKeyBoardPopupWindow.dismiss();
				// } else {
				textv.setText(showTv.getText());
				numberKeyBoardPopupWindow.dismiss();
				// }

			}
		});

		if (type) {
			cancelTv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					showTv.setText(showTv.getText().append("."));
					Selection.setSelection(showTv.getText(), showTv.getText().length());

				}
			});
		} else {
			numberKeyBoardPopupWindow.dismiss();
		}

		num0Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("0"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});
		num1Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("1"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});

		num2Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("2"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});
		num3Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("3"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});

		num3Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("3"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});
		num4Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("4"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});
		num5Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("5"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});

		num6Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("6"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});

		num7Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("7"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});
		num8Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("8"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});

		num9Tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTv.setText(showTv.getText().append("9"));
				Selection.setSelection(showTv.getText(), showTv.getText().length());

			}
		});

		numberKeyBoardPopupWindow.setTouchable(true);

		numberKeyBoardPopupWindow.setTouchInterceptor(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				// if (R.id.hourTv == textv.getId()) {
				// minuteTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// textv.setBackground(getResources().getDrawable(
				// R.drawable.shape_darkblueblackframe));
				// } else if (R.id.minuteTv == textv.getId()) {
				//
				// minuteTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// secondTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_darkblueblackframe));
				//
				// } else if (R.id.secondTv == textv.getId()) {
				//
				// secondTv.setBackground(getResources().getDrawable(
				// R.drawable.shape_blackframe));
				// }
				return false;
				// 这里如果返回true的话，touch事件将被拦截
				// 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
			}

		});

		numberKeyBoardPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		numberKeyBoardPopupWindow.setTouchable(true);
		numberKeyBoardPopupWindow.setOutsideTouchable(true);
		numberKeyBoardPopupWindow.showAtLocation(v, Gravity.CENTER, 200, 75);

	}

	private void dialog(final int index) {
		final AllShengDialog allShengDialog = new AllShengDialog(this, "", getString(R.string.getMessage), "No", "Yes");
		allShengDialog.setClicklistener(new ClickListenerInterface() {

			@Override
			public void Cancle() {
				// TODO Auto-generated method stub
				allShengDialog.dismiss();
				allShengDialog.cancel();
				upDatePopupWindow.dismiss();
				boolean ishave = false;
				for (int i = index; i < activityMethodBeans.size(); i++) {
					if (!TextUtils.isEmpty(activityMethodBeans.get(i).getGoTo())) {
						ishave = true;
					}
				}
				if (showTv.getText() == null || "".equals(showTv.getText())) {
					ByAlert.alert(getString(R.string.NoUpdateCycle4));
					allShengDialog.dismiss();
					upDatePopupWindow.dismiss();
				} else {
					if (ishave) {
						ByAlert.alert(getString(R.string.NoUpdateCycle1));
					} else if (Integer.parseInt(showTv.getText().toString()) <= Integer
							.parseInt(pointMaps.get(index - 1).get("repititions") + "")) {
						ByAlert.alert(getString(R.string.NoUpdateCycle2));
						allShengDialog.cancel();
					} else if (photoBackCount >= (Integer.parseInt(pointMaps.get(index - 1).get("repititions") + "")
							- 3)) {
						ByAlert.alert(getString(R.string.NoUpdateCycle3));
						allShengDialog.dismiss();
						upDatePopupWindow.dismiss();
					} else {
						Intent intent = new Intent("changePhotoBackCount");
						intent.putExtra("changePhotoBackCount", showTv.getText().toString());
						intent.putExtra("index", "" + (index - 1));
						sendBroadcast(intent);
						pointMaps.get(index - 1).put("repititions", showTv.getText().toString());
						activityMethodBeans.get(index - 1).setRepititions(showTv.getText().toString());
						ServiceMethodUtils methodUtils = new ServiceMethodUtils();
						methodUtils.updateRepititions(activityMethodBeans,
								intent.getStringExtra("changePhotoBackCount"));
						// 初始化
						mSimpleLineChart = BindView(R.id.simpleLineChart);
						mSimpleLineChart.setData(pointMap);
						mSimpleLineChart.setData2(pointMaps);
						String[] yItem = { "", "", "", "", "", "", "", "", "", "", "" };
						mSimpleLineChart.setYItem(yItem);

						// 编辑的思路：首先要全部读取（不加逗号），遇到关键信息删除。然后加上新内容。最后重写文件
						FileManagerUtil fileManagerUtil = new FileManagerUtil();
						String path = appFilePath + "/" + folderName;
						File file = new File(path + "/" + fileName);
						BufferedReader reader = null;
						contextString = new StringBuffer();

						try {
							System.out.println("以行为单位读取文件内容，一次读一整行:");
							reader = new BufferedReader(new FileReader(file));
							String tempString = null;
							int line = 1;
							// 一次读入一行，直到读入null为文件结束
							while ((tempString = reader.readLine()) != null) {
								// 显示行号
								// System.out.println("line " + line +
								// ": "
								// + tempString);
								// Log.e("--", tempString);

								if (tempString.contains("readDataString")) {
									contextString.append("\r\n");
									contextString.append(tempString);
									break;
								} else {
									if (line != 1) {
										contextString.append("\r\n");
									}

									contextString.append(tempString);

								}

								line++;
							}
							reader.close();
						} catch (IOException e) {
							e.printStackTrace();
						} finally {
							if (reader != null) {
								try {
									reader.close();
									// LogUtil.e("!!", contextString +
									// "");

								} catch (IOException e1) {
								}
							}
						}
						contextString.append("\r\n" + "\r\n" + "Methods" + "\r\n");

						for (MethodBean bean : activityMethodBeans) {
							contextString.append("\r\n" + "steptType: " + bean.getSteptType());
							contextString.append("\r\n" + "temperature: " + bean.getTemperature());
							contextString.append("\r\n" + "time: " + bean.getTime());
							contextString.append("\r\n" + "goTo: " + bean.getGoTo());
							contextString.append("\r\n" + "Repititions: " + bean.getRepititions());
							contextString.append("\r\n" + "deltaT: " + bean.getDeltaT());
							contextString.append("\r\n" + "rightSelect: " + bean.getRightSelect());

						}

						contextString.append("\r\n" + "\r\n" + "pointMap" + "\r\n");

						for (int i = 0; i < pointMap.size(); i++) {
							// pointMap.get(i)
							int index = i + 1;
							int result = 10 - Integer.parseInt(pointMap.get(i) + "");
							contextString.append("\r\n" + "pointMap" + index + ": " + result);

						}

						fileManagerUtil.createFIle(folderName, fileName);
						fileManagerUtil.writeFile(folderName, fileName, contextString + "", false);
						// 传值给扩增曲线
						LocalBroadcastManager localBroadcastManager;
						localBroadcastManager = LocalBroadcastManager.getInstance(RunMethodActivity.this);
						// IntentFilter intentFilter = new
						// IntentFilter("xValues"); // 过滤广播
						// myLocalReceiver = new MyLocalReceiver();
						// localBroadcastManager.registerReceiver(myLocalReceiver,
						// intentFilter); // 注册广播
						// IntentFilter iFilter = new IntentFilter("xValues");
						Intent intent1 = new Intent("xValues");
						intent1.putExtra("index", Integer.parseInt(showTv.getText().toString()));
						localBroadcastManager.sendBroadcast(intent1);

						upDatePopupWindow.dismiss();
						allShengDialog.dismiss();
					}
				}

			}

			@Override
			public void OK() {
				// TODO Auto-generated method stub
				upDatePopupWindow.dismiss();
				allShengDialog.dismiss();
				allShengDialog.cancel();
			}
		});
		if (null == allShengDialog || !allShengDialog.isShowing()) {
			allShengDialog.show();
		}
		// AlertDialog.Builder builder = new AlertDialog.Builder(this); //
		// 先得到构造器
		// builder.setTitle(getString(R.string.Message)); // 设置标题
		// builder.setMessage(getString(R.string.update_sure)); // 设置内容
		// builder.setPositiveButton(getString(R.string.hourActivity_confirm),
		// new DialogInterface.OnClickListener() { // 设置确定按钮
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// };
		// });
		// builder.setNegativeButton(getString(R.string.hourActivity_cancel),
		// new DialogInterface.OnClickListener() { // 设置取消按钮
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		//
		// }
		// });
		//
		// // 参数都设置完成了，创建并显示出来
		// if (!builder.create().isShowing()) {
		// builder.create().show();
		// }

	}

	class poponDismissListener implements PopupWindow.OnDismissListener {

		@Override
		public void onDismiss() {
			// TODO Auto-generated method stub
			backgroundAlpaha(RunMethodActivity.this, (1f));
		}

	}

	private boolean isForeground() {
		if (RunMethodActivity.this == null) {
			return false;
		}

		ActivityManager am = (ActivityManager) RunMethodActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(1);
		if (list != null && list.size() > 0) {
			ComponentName cpn = list.get(0).topActivity;
			if ("RunMethodActivity".equals(cpn.getClassName())) {
				return true;
			}
		}

		return false;
	}
}
